local t_util = require "libs/tableutil"
local FileHandle = {}


function FileHandle:DataFromJsonLine(path)
    return self:FuckDataFromJsonList(self:LineTableFromFile(path))
end
local MAP_ID_PREFIX,List_ID_PREFIX,Line_ID_PREFIX = "m_","l_","s_"
local uid,id = "hx","id"

function FileHandle:GetPrefix()
    return MAP_ID_PREFIX, List_ID_PREFIX, Line_ID_PREFIX
end
-- 各项是json的List根据huxi转Map或List
function FileHandle:FuckDataFromJsonList(t)
    local data = { }
    for _,line in pairs(t or {})do
        local re, line_data = xpcall(
            function() return json.decode(line) end, 
            function() end
        )
        if re then
            local long_id = tostring(line_data[uid])
            if long_id then
                local start = string.sub(long_id, 1, 2)
                local finish = string.sub(long_id, 3)
                if finish ~= "" then
                    if type(data[long_id])~="table" then
                        data[long_id] = {}
                    end
                    if start == MAP_ID_PREFIX then
                        local key = line_data[id]
                        if key then
                            data[long_id][key] = t_util:MergeMap(line_data)
                            data[long_id][key][id] = nil
                            data[long_id][key][uid] = nil
                        end
                    elseif start == List_ID_PREFIX then
                        table.insert(data[long_id], line_data)
                    elseif start == Line_ID_PREFIX then
                        line_data[uid] = nil
                        data[long_id] = line_data
                    end
                end
            end
        end
    end
    return data
end
-- 上面一个函数的反转，用于数据存储
function FileHandle:FuckTableToDataFile(path, t)
    local file = io.open(path, "w")
    local str = ""
    for long_id,uid_data in pairs(t)do
        local start = string.sub(long_id, 1, 2)
        local finish = string.sub(long_id, 3)
        if finish ~= "" then
            if start == MAP_ID_PREFIX then
                for key, l in pairs(uid_data)do
                    if type(l) == "table" then
                        l[id] = key
                        l[uid] = long_id
                        str = str..json.encode(l).."\n"
                    end
                end
            elseif start == List_ID_PREFIX then
                for _, l in pairs(uid_data)do
                    if type(l) == "table" then
                        l[uid] = long_id
                        str = str..json.encode(l).."\n"
                    end
                end
            elseif start == Line_ID_PREFIX then
                uid_data[uid] = long_id
                str = str .. json.encode(uid_data).."\n"
            end
        end
    end
    if file then
        file:write(str)
        file:close()
    else
        self:LogAddFile( "写入数据失败:", tostring(path), "原因：无法打开路径文件")
    end
end
function FileHandle:LineTableFromFile(path)
    if type(path) ~= "string" then
        return self:LogAddFile("打开文件路径错误：", tostring(path))
    end
    local file = io.open(path, "r")
    if not file then
        file = io.open(path, "w")
        file:close()
        return {}
    end
    local t = {}
    local ll_func = io.lines(path)
    for line in ll_func do
        table.insert(t, line)
    end
    return t
end

function FileHandle:ListFromJsonLine(path)
    local file = io.open(path, "r")
    if not file then
        io.open(path, "w"):close()
        return {}
    end
    local t = {}
    local ll_func = io.lines(path)
    for line in ll_func do
        local re, data = xpcall(
            function() return json.decode(line) end, 
            function() end
        )
        if re then
            table.insert(t, data)
        end
    end
    return t
end

function FileHandle:ListToJsonLine(path, t)
    local file = io.open(path, "w")
    local str = ""
    for _,l in pairs(t)do
        str = str..json.encode(l).."\n"
    end
    file:write(str)
    file:close()
end

function FileHandle:DataToJsonLine(path, t, a)
    local file = io.open(path, "w")
    local str = ""
    for key,l in pairs(t)do
        l.id = key
        str = str..json.encode(l).."\n"
    end
    local a = a or {}
    for _,l in pairs(a)do
        str = str..json.encode(l).."\n"
    end
    if file then
        file:write(str)
        file:close()
    else
        self:LogAddFile( "写入数据失败:", tostring(path))
    end
end



local log_path = "ShroomCakeFileSysLog.txt"
function FileHandle:LogAddFile(...)
    local str = table.concat({...}, " ")
    local data = self:LineTableFromFile(log_path)
    local file = io.open(log_path, "w")
    file:write(table.concat(data, "\n"))
    file:write("\n"..os.date().."  "..str)
    file:close()
    print(str)
end

return FileHandle
